import { Button, Dialog, Form, Input, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useRef, useState, useEffect } from 'react';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';

const FromItem = Form.Item;
const tableId = uniqueId('tauTable-');

const AddWhiteList = (props) => {
  const { activity, visible, onSubmit, onCancel, modal } = props;
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [formData] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current;
  const [state, setState] = useState([]);
  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量
  const { activityStore: store } = useStore();

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    _.assign(formData, activity);
    setState(activity?.whiteList);
    return (() => {
      _.set(formData, 'phone_user', '');
    });
  }, [visible]);

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const startIndex = currentPage * pageSize;
  const endIndex = startIndex + pageSize;
  const currentPageData = state.slice(startIndex, endIndex);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);

    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleAddUser = async () => {
    const { phone_user } = formData;
    if (!phone_user) {
      return Message.warning({ content: t`请输入手机号!` });
    }
    if (phone_user.length !== 11) {
      return Message.warning({ content: t`请输入正确手机号!` });
    }
    try {
      const findUser = state.find((p) => p === phone_user);
      if (findUser) {
        return Message.warning({ content: t`该手机号已存在!` });
      }
      const res = await store.getUserMobile(phone_user);
      if (res) {
        setState((pre) => {
          const arr = [...pre];
          arr.push(phone_user);
          return arr;
        });
      } else {
        Message.error({ content: t`该用户非平台用户!` });
      }
    } catch (error) {
      Message.error({ content: t`添加失败`, duration: 7000 });
      throw error;
    }
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleDeleteState = (i) => {
    setState((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    });
  };

  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    _.set(formData, 'whiteList', state);
    onSubmit?.(formData);
  };

  return (
    <Form
      inline
      value={formData}
      {...formProps}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <Form.Item
        label={t`手机号`}
        labelAlign="top"
        name="phone_user"
      >
        <Input
          style={{ width: 300 }}
          placeholder="请输入手机号"
          addonAfter={<Button type="primary" onClick={handleAddUser}>添加</Button>}
        />
      </Form.Item>
      <Form.Item
        label={t`白名单列表`}
        labelAlign="top"
        name="list"
      >
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={currentPage}
          pageSize={pageSize}
          total={state.length}
          onFetch={({ page, size }) => {
            setCurrentPage(page);
            size && setPageSize(size);
          }}
          dataSource={currentPageData}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.priceIdx(i, currentPage, pageSize) },
            {
              title: t`手机号`,
              dataIndex: '',
              width: 400,
              cell: (v, i, r) => r,
            },
            {
              title: t`操作`,
              dataIndex: '',
              cell: (v, i) => <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i, 'sc')}>{t`删除`}</Button>,
            },
          ]}
        />
      </Form.Item>
      <DrawerFooter>
        <FromItem>
          {<Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(AddWhiteList);
